<template>
  <div class="content">
    <div class="header">
      <el-row type="flex" justify="space-between">
        <el-col :span="12">
          <!-- <el-button
            class="searchBtn"
            size="small"
            type="success"
            icon="el-icon-s-check"
            @click="$router.push('/video/video/videoList')"
          >视频审核</el-button>
          <el-button
            class="searchBtn"
            size="small"
            type="primary"
            icon="el-icon-s-release"
            @click="$router.push('/video/video/contentList')"
          >内容管理</el-button>
          <el-button class="searchBtn" size="small" type="info" icon="el-icon-s-custom" @click="$router.push('/video/video/videoBlackList')">黑名单</el-button> -->
        </el-col>
        <el-col :span="12">
          <el-row type="flex" justify="end">
            <el-button class="searchBtn" size="small" type="primary" icon="el-icon-upload" @click="tapUpload">上传</el-button>
          </el-row>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :element-loading-text="g.loadingStr"
      :header-cell-style="{background:g.mainColor}"
    >
      <el-table-column prop="businessName" label="内容创作者" align="center" />
      <el-table-column prop="remark" label="作品简介" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryList.currentPage"
      :limit.sync="queryList.pageSize"
      @pagination="getList"
    />
    <el-dialog
      title="上传视频"
      :visible.sync="videoDialog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="450px"
      @close="closeVideo"
    >
      <el-form ref="ruleForm" label-position="left" :model="ruleForm" :rules="rules" label-width="0" class="demo-ruleForm">
        <el-form-item prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            maxlength="55"
            :autosize="{ minRows: 3, maxRows: 6}"
            show-word-limit
            placeholder="请输入介绍文案"
          />
        </el-form-item>
        <el-form-item prop="type">
          <el-radio-group v-model="ruleForm.type" @change="lableType">
            <el-radio :label="1">机构</el-radio>
            <el-radio :label="2">课程</el-radio>
            <el-radio :label="3">老师</el-radio>
          </el-radio-group>
          <div>标签:<span style="margin-left:10px;font-weight:600">{{ label.labelName||'请选择标签' }}</span></div>
        </el-form-item>
        <el-form-item prop="title">
          <div class="video-box">
            <div v-show="ruleForm.url" class="video">
              <video ref="myVideo" :src="ruleForm.url" controls="controls" />
              <div class="del" @click="ruleForm.url=''"><i class="el-icon-close" /></div>
            </div>
            <el-upload
              v-show="!ruleForm.url"
              ref="uploadVideo"
              class="avatar-uploader"
              accept=".mp4,.mov,.avi,.mpeg4"
              action="#"
              :show-file-list="false"
              :file-list="fileList"
              :before-upload="beforeAvatarUpload"
              :on-change="onChange"
              :on-progress="onProgress"
              :http-request="httpRequest"
              :auto-upload="false"
            >
              <i class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <div class="dialog-footer">
          <el-button type="danger" @click="videoDialog=false">取消</el-button>
          <el-button type="success" :loading="subLoading" @click="uploadVideo">上传</el-button>
        </div>
      </span>
    </el-dialog>

    <el-dialog
      title="选择标签"
      :visible.sync="typeDisalog"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      width="800px"
      @close="closeType"
    >
      <el-row style="margin-bottom:20px">
        <el-col :span="8">
          <el-input v-model="typePag.name" size="small" clearable placeholder="请输入名称搜索" class="input-with-select" @change="getType()">
            <el-button slot="append" icon="el-icon-search" />
          </el-input>
        </el-col>
      </el-row>
      <el-table
        :data="options"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        height="550px"
        :element-loading-text="g.loadingStr"
        :header-cell-style="{background:g.mainColor}"
      >
        <template v-if="ruleForm.type===1">
          <el-table-column :key="Math.random()" prop="logoImg" label="机构logo" align="center">
            <template slot-scope="{row}">
              <img style="width:60px" :src="row.logoImg">
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" prop="name" label="机构名称" align="center" />
          <el-table-column :key="Math.random()" prop="addressRemarks" label="机构地址" align="center" />
        </template>
        <template v-if="ruleForm.type===2">
          <el-table-column :key="Math.random()" label="课程图片" align="center">
            <template slot-scope="{row}">
              <img style="width:60px" :src="row.introducePictures">
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" prop="name" label="课程名称" align="center" />
          <el-table-column :key="Math.random()" prop="courseNatureName" label="课程性质" align="center" />
          <el-table-column :key="Math.random()" prop="businessName" label="机构名称" align="center" />
        </template>
        <template v-if="ruleForm.type===3">
          <el-table-column :key="Math.random()" label="老师头像" align="center">
            <template slot-scope="{row}">
              <img style="width:60px" :src="row.avatar">
            </template>
          </el-table-column>
          <el-table-column :key="Math.random()" prop="realName" label="老师名字" align="center" />
        </template>
        <el-table-column :key="Math.random()" label="操作" align="center">
          <template slot-scope="{row}">
            <el-button size="small" type="danger" @click="handleChoose(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :total="typeTotal"
        :page.sync="typePag.currentPage"
        :limit.sync="typePag.pageSize"
        @pagination="getType"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  worksPageList,
  // worksDeleteById,
  worksAdd,
  businessList,
  getUsers,
  courseList,
  worksDeleteById
} from '@/api/video'
import Pagination from '@/components/Pagination'
export default {
  name: 'VideoWorks',
  components: { Pagination },
  data() {
    return {
      queryList: {
        businessId: '',
        currentPage: 1,
        pageSize: 10
      },
      businessName: '',
      list: [],
      total: 0,
      subLoading: false,
      videoDialog: false,
      videoUrl: 'https://ossdev0.jiabala.com/ngZkLlkQqlIdb',
      fileList: [],
      fileInfo: {},
      typeDisalog: false,
      searchName: '',
      typePag: {
        name: '',
        currentPage: 1,
        pageSize: 10
      },
      typeTotal: 0,
      label: {
        labelId: '',
        labelName: '',
        labelLogo: ''
      },
      imgUrl: '',
      options: [// 视频类型(1.机构,2.课程,3.老师)
      ],
      businessInfo: {
        businessId: '',
        businessName: '',
        businessLogo: ''
      },
      ruleForm: {
        remark: '',
        url: '',
        labelId: '',
        type: ''
      },
      rules: {
        remark: [
          { required: true, message: '请输入介绍文案', trigger: 'blur' },
          { min: 3, max: 55, message: '长度在 3 到 55 个字符', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请上传视频作品', trigger: 'blur' }
        ],
        labelId: [
          { message: '请选择标签', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    const business = JSON.parse(this.$route.query.business)
    this.queryList.businessId = business.businessId || '0'
    this.businessInfo = business
    this.businessName = business.businessName
    this.getList()
  },
  methods: {
    handleDelete(row) {
      this.$confirm('是否删除此客户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        worksDeleteById({
          id: row.id
        }).then(res => {
          this.$message.success('删除成功')
          this.getList()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    tapUpload() {
      this.videoDialog = true
    },
    getType() {
      switch (this.ruleForm.type) {
        case 1:
          this.getBusinessList()
          break
        case 2:
          this.getCourseList()
          break
        case 3:
          this.getGetUsers()
          break
      }
    },
    getBusinessList() {
      businessList({
        ...this.typePag,
        businessId: this.queryList.businessId
      }).then(res => {
        this.options = res.data.records || []
        this.typeTotal = res.data.total || 0
      })
    },
    getGetUsers() {
      getUsers({
        ...this.typePag,
        businessId: this.queryList.businessId
      }).then(res => {
        this.options = res.data.records || []
        this.typeTotal = res.data.total || 0
      })
    },
    getCourseList() {
      courseList({
        ...this.typePag,
        businessId: this.queryList.businessId
      }).then(res => {
        this.options = res.data.records || []
        this.options.forEach(i => {
          i.introducePictures = i.introducePictures ? i.introducePictures.split(',')[0] : ''
        })
        this.typeTotal = res.data.total || 0
      })
    },
    lableType(type) {
      switch (type) {
        case 1:
          this.label = {
            labelId: this.queryList.businessId,
            labelName: this.businessName,
            labelLogo: this.businessInfo.logoImg
          }
          // this.getBusinessList()
          break
        case 2:
          this.typeDisalog = true
          this.getCourseList()
          break
        case 3:
          this.typeDisalog = true
          this.getGetUsers()
          break
      }
    },
    handleChoose(row) {
      // console.log(row, '///')
      switch (this.ruleForm.type) {
        case 1:
          this.label = {
            labelId: row.id,
            labelName: row.name,
            labelLogo: row.logoImg
          }
          break
        case 2:
          this.label = {
            labelId: row.id,
            labelName: row.categoryName,
            labelLogo: row.introducePictures ? row.introducePictures.split(',')[0] : ''
          }
          break
        case 3:
          this.label = {
            labelId: row.userId,
            labelName: row.realName,
            labelLogo: row.avatar
          }
          break
      }
      this.typeDisalog = false
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'video/mp4' || file.type === 'video/avi' || file.type === 'video/quicktime' || file.type === 'video/mpeg4'
      const isLt2M = file.size / 1024 / 1024 < 200

      if (!isJPG) {
        this.$message.error('只能上传视频')
      }
      if (!isLt2M) {
        this.$message.error('视频大小不能超过200m')
      }
      return isJPG && isLt2M
    },
    onProgress(event, file, fileList) {
      // console.log(event, file, fileList)
    },
    onChange(file, fileList) {
      console.log(file)

      this.ruleForm.url = URL.createObjectURL(file.raw)
      this.fileList = fileList.slice(-1)
    },
    async httpRequest(res) {
      const loading = this.$loading({
        lock: true,
        text: '视频上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const raw = {
        raw: res.file,
        name: res.file.name
      }
      await this.uploadImgToOss(raw).then(response => {
        this.videoUrl = response
      })
      const videoContent = this.$refs.myVideo
      const canvas = document.createElement('canvas')
      canvas.width = videoContent.videoWidth
      canvas.height = videoContent.videoHeight
      canvas.getContext('2d').drawImage(videoContent, 0, 0, canvas.width, canvas.height)
      canvas.toBlob(blod => {
        // console.log(blod, 'sssadad')
        const imgBlod = {
          raw: blod,
          name: Math.random() + '封面'
        }
        this.uploadImgToOss(imgBlod).then(response => {
          this.imgUrl = response
          worksAdd({
            'name': '',
            'labelId': this.label.labelId || '',
            'labelName': this.label.labelName || '',
            'labelLogo': this.label.labelLogo || '',
            'businessId': this.businessInfo.businessId,
            'businessName': this.businessInfo.businessName,
            'businessLogo': this.businessInfo.businessLogo || '',
            'type': this.ruleForm.type,
            'url': this.videoUrl,
            'imgUrl': response,
            'remark': this.ruleForm.remark
          }).then(res => {
            this.$message.success('上传成功')
            this.subLoading = false
            this.videoDialog = false
            this.getList()
            loading.close()
            this.ruleForm = {
              remark: '',
              url: ''
            }
            this.videoUrl = ''
          })
        })
      })
    },
    uploadVideo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.subLoading = true
          this.$refs.uploadVideo.submit()
        } else {
          return false
        }
      })
    },
    closeVideo() {
      this.ruleForm = {
        remark: '',
        url: ''
      }
      this.videoUrl = ''
      this.fileList = []
      this.label = {
        labelId: '',
        labelName: '',
        labelLogo: ''
      }
    },
    closeType() {
      this.typePag = {
        name: '',
        currentPage: 1,
        pageSize: 10
      }
    },
    getList() {
      worksPageList(this.queryList).then((res) => {
        const { total, records } = res.data
        this.list = records
        this.total = total
      })
    }
  }
}
</script>

<style scoped lang='scss'>
.content {
  padding: 10px;
  .header{
      margin-bottom: 15px;
  }
  .video-box{
    display: flex;
    flex-wrap: wrap;
    .video{
      position: relative;
      margin-right: 15px;
      width: 200px;
      transition: all 1s ease-in-out;
      .del{
        cursor: pointer;
        position: absolute;
        top: -10px;
        right: -10px;
        display: flex;
        justify-content: center;
        align-items: center;
        width:30px;
        height:30px;
        font-size: 24px;
        color: #fff;
        background: red;
        border-radius: 50%;
      }
      >video{
        width:100%;
      }
    }
    .video-title{
      margin-bottom: 20px;
      font-size: 14px;
      font-weight: 500;
      color: rgb(80, 80, 80);
    }
  }
  .dialog-footer{
    width: 100%;
    text-align: center !important;
  }
}
  /deep/.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  /deep/.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  /deep/.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  /deep/.avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
</style>
